package com.epam.facebook_client;

import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewPager;

import com.epam.facebook_client.content.contract.AppContract;
import com.epam.facebook_client.manager.ImageManager;
import com.epam.facebook_client.wrapper.Photos;
import common.adapters.AbstractPagerAdapter;

public class PhotosPageActivity extends FragmentActivity implements LoaderCallbacks<Cursor>{

	private String TAG = PhotosPageActivity.class.getSimpleName();
	
	private ImageManager imageManager;
	
	private int itemPosition;
	
	private String idAlbum;
	
	private ViewPager viewPager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		imageManager = ImageManager.get(this);
		viewPager = new ViewPager(this);
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			itemPosition = extras.getInt(PhotosActivity.POSITION);
			idAlbum = extras.getString(PhotosActivity.ID_ALBUM);
		} else {
			finish();
		}
		setContentView(viewPager);
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		getSupportLoaderManager().initLoader(0, null, this);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		String[] selectionArgs = { idAlbum };
		String[] projection = { AppContract.PhotosColumns.SOURCE };
		return new CursorLoader(this, AppContract.PhotosColumns.CONTENT_URI, projection,
				AppContract.PhotosColumns.ALBUM_ID + " = ?", selectionArgs, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
		if (cursor.getCount() > 0) {
			String[] columnNames = { AppContract.PhotosColumns.SOURCE };
			int[] viewId = { R.id.photo_imageview };
			AbstractPagerAdapter<Photos> adapter = new AbstractPagerAdapter<Photos>(this, cursor, imageManager, viewId, columnNames) {

				@Override
				public int getResources() {
					return R.layout.activity_photos_pager;
				}
			};
			viewPager.setAdapter(adapter);
			viewPager.setCurrentItem(itemPosition);
		}
		
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		
	}
}
